package admin;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;

import test.CSV_Handler;
import test.DateTools;
import test.LocalProperties;


import com.objective.oji.OjiCatalogue;
import com.objective.oji.OjiCatalogueFieldDefinition;
import com.objective.oji.OjiDocument;
import com.objective.oji.OjiException;
import com.objective.oji.OjiObject;
import com.objective.oji.OjiSearch;
import com.objective.oji.OjiTypeDefn;

public class Obj_Search extends LocalObjSession {

    public Obj_Search(LocalProperties AppProfile, SERVER_TYPE Selected_SERVER_PROFILE, LOGINMETHOD Login_Method_TYPE) {
	super(AppProfile, Selected_SERVER_PROFILE, Login_Method_TYPE);
    }

    public boolean search() throws OjiException {
	/*
	 * SEARCH ---------------------------
	 */
	int Max_return_count = 1000;
	Search_Builder newSearch = new Search_Builder(apiSession, Max_return_count);

	try {
	    newSearch.set_Search_type("folder");
	    newSearch.addCriteria("name", "begins", "a");
	} catch (OjiException e) {
	    e.printStackTrace();
	}

	Collection<OjiObject> searchReturns;
	searchReturns = newSearch.execute();
	Iterator<OjiObject> i = searchReturns.iterator();

	while (i.hasNext()) {
	    OjiObject searchResult = i.next();
	    System.out.println("Id :" + searchResult.getObjId() + ", Name :" + searchResult.getLabelForView());
	}
	return true;
    }


    public boolean search_diff_missing_sheet_number_on_drawingname() {

	int Max_return_count = 500;
	final boolean CSV_OUTPUT = true;

	DateTools ts = new DateTools();
	String filepath = "C:\\Search-" + ts.getDateTime() + ".csv";
	CSV_Handler CSV_File = new CSV_Handler("|", filepath);

	try {
	    OjiSearch newSearch = apiSession.initAdvancedSearch();
	    newSearch.setMaximumResults(Max_return_count);

	    OjiTypeDefn search_type = apiSession.getTypeDefnByName("Transmission Drawing");
	    newSearch.setObjectSearchType(search_type);
	    newSearch.addCriteria("Sheet Number", "is greater than", "1", 0, 0, OjiSearch.AND_RELATION);
	    newSearch.execute();

	    Collection<OjiObject> results = newSearch.getResults();
	    Iterator<OjiObject> i = results.iterator();

	    /*
	     * List of Fields
	     */
	    List<String> fields = new ArrayList<String>();
	    fields.add("ID");
	    fields.add("Name");
	    fields.add("Sheet Number");
	    fields.add("Number");

	    Iterator<String> it_title = fields.iterator();
	    while (it_title.hasNext()) {
		String value = it_title.next();
		CSV_File.AddElement(value);
	    }
	    CSV_File.NextLine();

	    /*
	     * Print RECORD
	     */

	    while (i.hasNext()) {
		OjiObject searchResult = i.next();
		OjiDocument myDoc = (OjiDocument) apiSession.getObject(searchResult.getObjId());
		String drawing_name = myDoc.getName().trim();
		String drawing_number = myDoc.getFieldValueByName("Drawing Number");
		String sheet_number = myDoc.getFieldValueByName("Sheet Number");

		if (drawing_name.trim().equals(drawing_number.trim())) {

		} else {
		    CSV_File.AddElement(searchResult.getObjId());
		    CSV_File.AddElement(drawing_name);
		    CSV_File.AddElement(sheet_number);
		    CSV_File.AddElement(drawing_number);
		    CSV_File.NextLine();
		}
	    }

	    CSV_File.WriteAll();
	    System.out.println("Max Return Result is set to " + Max_return_count);
	    System.out.println("TOTAL COUNT: " + results.size());

	} catch (OjiException e) {
	    System.out.println("QUERY FAILED");
	}
	return true;
    }

    public boolean search_diff_name_and_number() {

	/*
	 * Print RESULTS
	 */

	int Max_return_count = 20000;

	// DATE FORMAT "29-1-2006 22:01:01"
	String beginDATE = "1-1-2011 00:00:01";
	String endDATE = "1-1-2012 00:00:01";

	int loop_count = 0;

	while (loop_count < 1) {
	    try {

		final boolean CSV_OUTPUT = true;
		DateTools ts = new DateTools();
		String filepath = "C:\\Search-" + ts.getDateTime() + ".csv";
		CSV_Handler CSV_File = new CSV_Handler("|", filepath);

		/*
		 * Print HEADER
		 */
		List<String> fields = new ArrayList<String>();
		fields.add("ID");
		fields.add("Name");
		fields.add("Sheet Number");
		fields.add("Number");

		Iterator<String> it_title = fields.iterator();
		while (it_title.hasNext()) {
		    String value = it_title.next();
		    CSV_File.AddElement(value);
		}
		CSV_File.NextLine();

		// beginDATE = endDATE;
		// endDATE = getDateString( beginDATE, (1000*60*60*1));

		Search_Builder newSearch = new Search_Builder(apiSession, Max_return_count);
		newSearch.set_Search_type("Transmission Drawing");
		newSearch.addCriteria("creation date", "is after", beginDATE);
		newSearch.addCriteria("creation date", "is on or before", endDATE);

		Collection<OjiObject> searchReturns;
		searchReturns = newSearch.execute();
		loop_count = loop_count + 1;
		System.out.println("beginDATE: " + beginDATE);
		System.out.println("return: " + searchReturns.size());

		Iterator<OjiObject> i = searchReturns.iterator();

		while (i.hasNext()) {
		    OjiObject searchResult = i.next();
		    OjiDocument myDoc = (OjiDocument) apiSession.getObject(searchResult.getObjId());
		    String drawing_name = myDoc.getName().trim();
		    String drawing_date = myDoc.getDateCreate().toString();
		    String drawing_number = myDoc.getFieldValueByName("Drawing Number").trim();
		    String sheet_number = myDoc.getFieldValueByName("Sheet Number").trim();

		    if (drawing_name.equals(drawing_number)) {

		    } else {
			CSV_File.AddElement(searchResult.getObjId());
			CSV_File.AddElement(drawing_name);
			CSV_File.AddElement(sheet_number);
			CSV_File.AddElement(drawing_number);
			CSV_File.AddElement(drawing_date);
			CSV_File.NextLine();
		    }
		}

		CSV_File.WriteAll();

	    } catch (OjiException e) {
		e.printStackTrace();
	    }
	}
	/*
	 * BufferedReader br2 = new BufferedReader(new InputStreamReader(System.in)); try { String
	 * selected =
	 * br2.readLine(); } catch (IOException e) { System.exit(1); }
	 * System.out.println("Max Return Result is set to "
	 * + Max_return_count);
	 */
	return true;
    }

    public int search_drawing_count() {

	int Max_return_count = 500;
	final boolean CSV_OUTPUT = true;
	int total_count = 0;

	DateTools ts = new DateTools();

	try {
	    OjiSearch newSearch = apiSession.initAdvancedSearch();
	    newSearch.setMaximumResults(Max_return_count);

	    OjiTypeDefn search_type = apiSession.getTypeDefnByName("user");
	    newSearch.setObjectSearchType(search_type);
	    newSearch.setTextQuery("SELECT * FROM objective_own.users");
	    // newSearch.addCriteria("Sheet Number", "is greater than", "1",
	    // 0,0, OjiSearch.AND_RELATION);
	    newSearch.execute();

	    Collection<OjiObject> results = newSearch.getResults();

	    System.out.println("_________________________________");
	    System.out.println("Max Return Result is set to " + Max_return_count);
	    total_count = results.size();
	    System.out.println("TOTAL COUNT: " + total_count);

	    Iterator<OjiObject> i = results.iterator();

	} catch (OjiException e) {
	    System.out.println("QUERY FAILED");
	}

	return total_count;
    }

    public int search_drawing_count2() {

	int Max_return_count = 500000;
	int total_count = 0;
	DateTools ts = new DateTools();

	try {

	    Search_Builder newSearch = new Search_Builder(apiSession, Max_return_count);
	    newSearch.set_Search_type("Distribution Drawing");
	    // userSearch.addCriteria("date inactivated", "is blank", "");

	    Collection<OjiObject> results = newSearch.execute();

	    Iterator<OjiObject> i = results.iterator();

	    System.out.println("_________________________________");
	    System.out.println("Max Return Result is set to " + Max_return_count);
	    total_count = results.size();
	    System.out.println("TOTAL COUNT: " + total_count);

	} catch (OjiException e) {
	    System.out.println("QUERY FAILED");
	}

	return total_count;
    }

    public List<String> Search_GetObjID(String type, String attr, String cond, String filter) {
	/*
	 * SEARCH extended - retrieve record(s) --------------------------- more practical approach
	 * to list all matching
	 * search results
	 */
	int Max_return_count = 1000;
	Search_Builder newSearch = new Search_Builder(apiSession, Max_return_count);

	try {
	    newSearch.set_Search_type(type);
	    newSearch.addCriteria(attr, cond, filter);
	} catch (OjiException e) {
	    e.printStackTrace();
	}

	List<String> resultset_list = new ArrayList<String>();

	Collection<OjiObject> searchReturns;
	searchReturns = newSearch.execute();
	Iterator<OjiObject> i = searchReturns.iterator();

	while (i.hasNext()) {
	    OjiObject searchResult = i.next();
	    System.out.println("Id :" + searchResult.getObjId() + ", Name :" + searchResult.getLabelForView());
	    resultset_list.add(searchResult.getObjId());
	}

	return resultset_list;
    }

    public boolean search_list_diff() {

	int Max_return_count = 1000;
	Search_Builder newSearch_Alias = new Search_Builder(apiSession, Max_return_count);

	try {
	    newSearch_Alias.set_Search_type("alias");
	    newSearch_Alias.addCriteria("parent group", "is", "gA25");
	} catch (OjiException e) {
	    e.printStackTrace();
	}

	return true;

    }

    public boolean search_list_doc() {

	int Max_return_count = 200;

	DateTools ts = new DateTools();
	String filepath = "C:\\Search-" + ts.getDateTime() + ".csv";
	CSV_Handler CSV_File = new CSV_Handler("|", filepath);

	try {
	    OjiSearch newSearch = apiSession.initAdvancedSearch();
	    newSearch.setMaximumResults(Max_return_count);

	    // OjiTypeDefn search_type =
	    // apiSession.getTypeDefnByName("document");
	    OjiTypeDefn search_type = apiSession.getTypeDefnByName("Distribution Drawing");
	    // OjiTypeDefn search_type =
	    // apiSession.getTypeDefnByName("duotA2, duotA15, duotA16");

	    newSearch.setObjectSearchType(search_type);

	    /*
	     * SEARCH CRITERIA ======== Area/Region = EAST PARENT = As Below VK5 - qA7932 (12786)
	     * VK7 - qA7934 (540) VK8
	     * - qA7935 (3287) VK11 - qA7924 (120) VK15 - qA7926 (502) per 21/Mar/2011 from
	     * Objective Client Search
	     */
	    newSearch.addCriteria("Area/Region", "is exactly", "East", 0, 0, OjiSearch.AND_RELATION);
	    newSearch.addCriteria("Parent", "is", "qA7924", 0, 0, OjiSearch.AND_RELATION);

	    newSearch.execute();

	    Collection<OjiObject> results = newSearch.getResults();
	    Iterator<OjiObject> i = results.iterator();

	    System.out.println("_________________________________");
	    System.out.println("Max Return Result is set to " + Max_return_count);
	    System.out.println("TOTAL COUNT: " + results.size());
	    /*
	     * List of Fields
	     */
	    List<String> fields = new ArrayList<String>();
	    fields.add("Area/Region");
	    /*
	     * Print TITLE
	     */
	    CSV_File.AddTitleFields("ID|Name|Parent");

	    Iterator<String> it_title = fields.iterator();
	    while (it_title.hasNext()) {
		String value = it_title.next();
		CSV_File.AddElement(value);
	    }
	    CSV_File.NextLine();

	    /*
	     * Print RECORD
	     */

	    while (i.hasNext()) {
		OjiObject searchResult = i.next();

		OjiDocument myDoc = (OjiDocument) apiSession.getObject(searchResult.getObjId());
		OjiObject myDocParent = (OjiObject) myDoc.getParent();

		CSV_File.AddElement(searchResult.getObjId());
		CSV_File.AddElement(searchResult.getLabelForView());
		CSV_File.AddElement(myDocParent.getName());

		try {
		    OjiCatalogue cat = (OjiCatalogue) myDoc.getCatalogue();
		    List<OjiCatalogueFieldDefinition> fields2 = cat.getFields();
		    List<OjiCatalogueFieldDefinition> aa = fields2;
		    Iterator<OjiCatalogueFieldDefinition> i_aa = aa.iterator();
		    while (i_aa.hasNext()) {
			OjiCatalogueFieldDefinition value1 = i_aa.next();
			System.out.println(value1);
		    }

		} catch (OjiException e) {
		    System.err.println("Error: " + e.getMessage());
		    e.printStackTrace();
		}

		CSV_File.NextLine();

		// .getKeywordsAssigned

		Iterator<String> it = fields.iterator();

		while (it.hasNext()) {
		    // System.out.format("%s", value);
		    String value = it.next();
		    CSV_File.AddElement(myDoc.getFieldValueByName(value));
		}
		CSV_File.NextLine();
	    }
	    CSV_File.WriteAll();

	} catch (OjiException e) {
	    System.out.println("QUERY FAILED");
	}

	return true;
    }


    public boolean Search_multi_input_csv(String filepath_drawing_list) {

	/*
	 * SEARCH --------------------------- 1.READ USER INPUT FILE from C:\DEV\INPUT 2.BUILD USER
	 * ARRAY 3.SEARCH THE
	 * USER from OBJECTIVE 4.LIST MATCHED USERS on SCREEN NOTE internalName - Either the name of
	 * an Objective's
	 * object type ("any object", "file", "folder", "document", etc)or the id of an object
	 * sub-type. If the
	 * parameter provided doesn't match any object type, "any object" is used instead. For
	 * Advanced Search: Can also
	 * contain multiple internal object type names, separated by commas.
	 */

	List<String> userID_list = new ArrayList<String>();

	try {
	    FileInputStream fstream = new FileInputStream(filepath_drawing_list);
	    DataInputStream in = new DataInputStream(fstream);
	    BufferedReader br = new BufferedReader(new InputStreamReader(in));
	    String strLine;
	    while ((strLine = br.readLine()) != null) {
		if (strLine.length() > 5) {
		    userID_list.add(strLine);
		    System.out.println("> Line Added - " + strLine);
		}
	    }
	    in.close();
	} catch (Exception e) {
	    System.err.println("Error: " + e.getMessage());
	    e.printStackTrace();
	}

	System.out.println("\n \n :Search results----------------------- \n");
	Iterator<String> it = userID_list.iterator();
	String Object_Name;

	while (it.hasNext()) {
	    String textLine = it.next();
	    String[] strArray;
	    String str_id;
	    String object_id;

	    strArray = textLine.split("\\,"); // CSV
	    Object_Name = strArray[0].trim();

	    try {
		OjiSearch newSearch = apiSession.initAdvancedSearch();
		OjiTypeDefn search_type = apiSession.getTypeDefnByName("document");
		// OjiTypeDefn search_type =
		// apiSession.getTypeDefnByName("duotA2, duotA15, duotA16");

		// System.out.println(search_type.getSingularName());
		newSearch.setObjectSearchType(search_type);
		newSearch.addCriteria("name", "is exactly", Object_Name, 0, 0, OjiSearch.AND_RELATION);
		newSearch.execute();

		Collection<OjiObject> results = newSearch.getResults();
		Iterator<OjiObject> i = results.iterator();

		while (i.hasNext()) {
		    OjiObject searchResult = i.next();
		    object_id = searchResult.getObjId();
		    OjiDocument myDoc = (OjiDocument) apiSession.getObject(object_id);
		    System.out.println(object_id + "," + myDoc.getName() + "," + myDoc.getFieldValueByName("Line 1"));
		}

	    } catch (OjiException e) {
		System.out.println("QUERY FAILED");
		System.err.println("Error: " + e.getMessage());
		e.printStackTrace();
	    }
	}
	return true;
    }
    public boolean list_catalogue() {

	try {
	    /*
	     * SQL: select * from &owner.catalogues order by name; cA17 - Distribution TYPE
	     * Catalogue cA2 - Transmission
	     * Drawing Type Catalogue cA18 - Subtransmission Drawing Type Catalogue
	     */

	    String catalog_id = "cA2";

	    OjiCatalogue myCatalog = (OjiCatalogue) apiSession.getObject(catalog_id);
	    List<OjiCatalogueFieldDefinition> list_cat = myCatalog.getFields();
	    Iterator<OjiCatalogueFieldDefinition> i_list = list_cat.iterator();
	    while (i_list.hasNext()) {
		OjiCatalogueFieldDefinition field1 = i_list.next();
		System.out.println(field1.getName());
	    }

	} catch (OjiException e) {
	    System.out.println("List Catalogue failed");
	    System.err.println("Error: " + e.getMessage());
	    e.printStackTrace();
	}
	return true;
    }
}
